﻿using FreeSql;
using FreeSql.Internal;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using MySqlX.XDevAPI.Relational;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Db;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Core.Helpers;
using ZhonTai.Admin.Services;
using ZhonTai.Common.Extensions;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.Industry.Domain.WorkParamRecord;
using ZhonTai.Industry.Domain.WorkStation;
using ZhonTai.Industry.Domain.WorkStationRecord;
using ZhonTai.Industry.Resources;
using ZhonTai.Industry.Services.WorkParamRecord.Dto.Output;
using ZhonTai.Industry.Services.WorkStationRecord.Dto.Input;
using ZhonTai.Industry.Services.WorkStationRecord.Dto.Output;
using OfficeOpenXml;
using Org.BouncyCastle.Asn1.Crmf;
using System.Reflection;
using FreeSql.DataAnnotations;
using Minio.DataModel;
using ZhonTai.Industry.Domain.ProductModel;
using ZhonTai.Admin.Services.TaskScheduler;
using Newtonsoft.Json;
using ZhonTai.Admin.Services.TaskScheduler.Dto;
using FreeScheduler;
using System.Reactive.Concurrency;
using Microsoft.AspNetCore.Hosting;
using ZhonTai.Industry.Services.Background;
using Magicodes.ExporterAndImporter.Excel.AspNetCore;
using System.Diagnostics;
using COSXML.Network;
using ZhonTai.Industry.Domain.ProductionLine;
using ZhonTai.Industry.Domain.ProductionQuantity;
using ZhonTai.Industry.Repositories.ProductionQuantity;
using Scheduler = FreeScheduler.Scheduler;
using static COSXML.Model.Tag.InventoryConfiguration;

namespace ZhonTai.Industry.Services.WorkStationRecord
{
    /// <summary>
    /// 产品过站记录服务
    /// </summary>
    [DynamicApi(Area = IndustryConsts.AreaName)]
    public class WorkStationRecordService : BaseService, IWorkStationRecordService, IDynamicApi
    {
        public IWorkStationRecordRepository workStationRecordRepository => LazyGetRequiredService<IWorkStationRecordRepository>();
        public BackgroundService _backgroundService;
        private readonly IEHelper _iEHelper;
        private readonly IndustryLocalizer _industryLocalizer;
        private IWorkStationRepository workStationRepository => LazyGetRequiredService<IWorkStationRepository>();
        public IWorkParamRecordRepository workParamRecordRepository => LazyGetRequiredService<IWorkParamRecordRepository>();
        public IProductQuantityRepository productQuantityRepository => LazyGetRequiredService<IProductQuantityRepository>();

        public WorkStationRecordService(IndustryLocalizer industryLocalizer, IEHelper iEHelper, BackgroundService backgroundService)
        {
            _backgroundService = backgroundService;
            _industryLocalizer = industryLocalizer;
            _iEHelper = iEHelper;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<WorkStationRecordOutput> GetAsync(long id)
        {
            var output = await workStationRecordRepository.GetAsync<WorkStationRecordOutput>(id);
            return output;
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<WorkStationRecordGetListOutput>> GetListAsync(WorkStationRecordGetListInput input)
        {
            var list = await workStationRecordRepository.Select
                .WhereIf(!input.ProductCode.IsNull(), a => a.ProductCode == input.ProductCode)
                .WhereIf(input.StationId.HasValue, w => w.StationId == input.StationId)
                .OrderByDescending(a => a.Id)
                .ToListAsync(t =>
                new WorkStationRecordGetListOutput
                {
                    StationCode = t.WorkStation.StationCode,
                    StationName = t.WorkStation.StationName,
                    LineCode = t.WorkStation.ProductionLine.LineCode,
                    LineName = t.WorkStation.ProductionLine.LineName,
                    ProductModelCode = t.ProductModel.ProductCode,
                    ProductModelName = t.ProductModel.ProductName
                });
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<WorkStationRecordGetPageOutput>> GetPageAsync(PageInput<WorkStationRecordGetPageInput> input)
        {
            var filter = input.Filter;
            var tableNames = GetTableFilter(filter); // 根据时间范围获取相关分表名

            var allRecords = new List<WorkStationRecordGetPageOutput>();
            long total = 0;
            foreach (var tableName in tableNames)
            {
                // 单分表查询（注意：分页参数需传递到每个分表查询）
                var query = workStationRecordRepository.Select
                    .AsTable((type, old) =>
                    {
                        if (type == typeof(WorkStationRecordEntity))
                            return tableName;
                        if (type == typeof(WorkStationEntity))
                            return "cfg_work_station";
                        if (type == typeof(ProductionLineEntity))
                            return "cfg_production_line";
                        if (type == typeof(ProductModelEntity))
                            return "prd_product_model";
                        return old;
                    })
                    .Include(i => i.WorkStation)
                    .Include(i => i.ProductModel)
                    .WhereDynamicFilter(input.DynamicFilter)
                    .WhereIf(filter.StartTime != null, x => x.CreatedTime >= filter.StartTime)
                    .WhereIf(filter.EndTime != null, x => x.CreatedTime <= filter.EndTime)
                    .WhereIf(filter.StationId > 0, w => w.StationId == filter.StationId)
                    .Count(out var conut);

                // 动态排序（单表内排序）
                if (input.SortList?.Count > 0)
                {
                    input.SortList.ForEach(sort =>
                        query = query.OrderByPropertyNameIf(sort.Order.HasValue, sort.PropName, sort.IsAscending.Value));
                }
                else
                {
                    query = query.OrderByDescending(x => x.CreatedTime);
                }

                // 获取该分表符合条件的全部数据（或分批读取）
                var records = await query
                    .Page(input.CurrentPage, input.PageSize)
                    .ToListAsync(r => new WorkStationRecordGetPageOutput
                    {
                        StationCode = r.WorkStation.StationCode,
                        StationName = r.WorkStation.StationName,
                        LineCode = r.WorkStation.ProductionLine.LineCode,
                        LineName = r.WorkStation.ProductionLine.LineName,
                        ProductModelCode = r.ProductModel.ProductCode,
                        ProductModelName = r.ProductModel.ProductName,
                        CreatedTime = r.CreatedTime
                    });

                allRecords.AddRange(records);
                total += conut;
            }

            // 全局内存排序
            var orderedRecords = allRecords.OrderByDescending(x => x.CreatedTime).ToList();

            // 内存分页
            var pagedList = orderedRecords
                .Take(input.PageSize)
                .ToList();

            return new PageOutput<WorkStationRecordGetPageOutput>
            {
                List = pagedList,
                Total = total
            };
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> AddAsync(WorkStationRecordAddInput input)
        {
            var entity = Mapper.Map<WorkStationRecordEntity>(input);
            var id = (await workStationRecordRepository.InsertAsync(entity)).Id;

            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task UpdateAsync(WorkStationRecordUpdateInput input)
        {
            var entity = await workStationRecordRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("产品过站信息不存在！");
            }

            Mapper.Map(input, entity);
            await workStationRecordRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteAsync(long id)
        {
            return await workStationRecordRepository.DeleteAsync(id) > 0;
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> SoftDeleteAsync(long id)
        {
            return await workStationRecordRepository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> BatchSoftDeleteAsync(long[] ids)
        {
            return await workStationRecordRepository.SoftDeleteAsync(ids);
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NonFormatResult]
        public async Task<ActionResult> ExportDataAsync(ExportInput input)
        {
            using var _ = workStationRecordRepository.DataFilter.DisableAll();
            var select = workStationRecordRepository.Select;
            if (input.SortList != null && input.SortList.Count > 0)
            {
                select = select.SortList(input.SortList);
            }
            else
            {
                select = select.OrderBy(o => o.Id);
            }
            var dataList = await select.WhereDynamicFilter(input.DynamicFilter).ToListAsync(t => new WorkStationRecordExport()
            {
                StationCode = t.WorkStation.StationCode,
                StationName = t.WorkStation.StationName,
                LineCode = t.WorkStation.ProductionLine.LineCode,
                LineName = t.WorkStation.ProductionLine.LineName,
                ProductModelCode = t.ProductModel.ProductCode,
                ProductModelName = t.ProductModel.ProductName
            });
            //导出数据
            var fileName = input.FileName.NotNull() ? input.FileName : _industryLocalizer["产品过站记录-{0}列表{1}.xlsx", _industryLocalizer["当前产品"], DateTime.Now.ToString("yyyyMMddHHmmss")];

            return await _iEHelper.ExportDataAsync(dataList, fileName, _industryLocalizer["当前产品"]);
        }

        /// <summary>
        /// 计算当前加工计数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ProcessDataResultOutput> ComputeProcessDataAsync()
        {
            var onlinestations = await workStationRepository.Select.Where(w => w.StationType.Equals("Online")).ToListAsync(t => t.Id);
            var offlinestations = await workStationRepository.Select.Where(w => w.StationType.Equals("Offline")).ToListAsync(t => t.Id);
            if (onlinestations.Count == 0 && offlinestations.Count == 0)
            {
                return new ProcessDataResultOutput() { NgChangeRatio = 0, OkToday = 0, OkChangeRatio = 0, TotalChangeRatio = 0, TotalToday = 0 };
            }
            DateTime today = DateTime.Today;
            var todayStart = today;
            var todayEnd = today.AddDays(1).AddSeconds(-1);

            DateTime yesterday = today.AddDays(-1);
            var yesterdayStart = yesterday;
            var yesterdayEnd = yesterday.AddDays(1).AddSeconds(-1);

            // 查询今日数据
            var totalToday = await workStationRecordRepository.Select
                .Where(r => onlinestations.Contains(r.StationId)
                    && r.CreatedTime >= todayStart
                    && r.CreatedTime <= todayEnd)
                .CountAsync();

            var okToday = await workStationRecordRepository.Select
                .Where(r => offlinestations.Contains(r.StationId)
                    && r.CreatedTime >= todayStart
                    && r.CreatedTime <= todayEnd
                && r.Result == "OK")
                .CountAsync();
            var dailyEntity = await productQuantityRepository.Select
                .Where(x => x.DailyTime == DateTime.Today)
                .ToOneAsync();
            if (dailyEntity == null)
            {
                ProductionQuantityEntity dailyCount = new ProductionQuantityEntity
                {
                    DailyTime = DateTime.Today,
                    OnlineCount = totalToday,
                    OfflineCount = okToday
                };
                await productQuantityRepository.InsertAsync(dailyCount);
            }
            else
            {
                dailyEntity.OnlineCount = totalToday;
                dailyEntity.OfflineCount = okToday;
                await productQuantityRepository.UpdateAsync(dailyEntity);
            }
            // 查询昨日数据
            var yesterdayCount = await productQuantityRepository.Select
                .Where(x => x.DailyTime == DateTime.Today.AddDays(-1))
                .ToOneAsync();
            if (yesterdayCount == null)
            {
                yesterdayCount = new ProductionQuantityEntity() { OnlineCount = 0, OfflineCount = 0 };
            }
            // 计算变化率
            double totalChangeRatio = CalculateChangeRatio(totalToday, yesterdayCount.OnlineCount);
            double okChangeRatio = CalculateChangeRatio(okToday, yesterdayCount.OfflineCount);
            double ngChangeRatio = CalculateChangeRatio(totalToday - okToday, yesterdayCount.OnlineCount - yesterdayCount.OfflineCount);

            return new ProcessDataResultOutput
            {
                TotalToday = totalToday,
                OkToday = okToday,
                TotalChangeRatio = totalChangeRatio,
                NgChangeRatio = ngChangeRatio,
                OkChangeRatio = okChangeRatio
            };
        }

        private double CalculateChangeRatio(long current, long previous)
        {
            if (previous == 0)
            {
                return current == 0 ? 0 : 100.0;
            }
            return Math.Round((double)(current - previous) / previous * 100, 2);
        }

        /// <summary>
        /// 计算近几日加工计数
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<RecentlyProcessOutput>> ComputeRecentlyProcessAsync(int input)
        {
            var prductQuantityList = await productQuantityRepository.Select
                .Take(input)
                .OrderByDescending(x => x.DailyTime)
                .ToListAsync();
            var recentlyList = prductQuantityList.Select(x => new RecentlyProcessOutput() { OnlineCount = x.OnlineCount, OfflineCount = x.OfflineCount }).ToList();
            return recentlyList;
        }

        /// <summary>
        /// 导出生产数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task ExportProcessDataAsync(WorkStationExportInput input)
        {
            _ = Task.Run(async () =>
             {
                 await _backgroundService.WriteDataExcelAsync(input);
             });
        }

        /// <summary>
        /// 导出进度
        /// </summary>
        /// <param name="cacheId"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<double> ExportProgressAsync()
        {
            return Convert.ToDouble(await Cache.GetAsync(CacheKey.ExportProgress));
        }

        /// <summary>
        /// 导出缓存文件
        /// </summary>
        /// <param name="cacheId"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> ExportFileNameAsync()
        {
            return await Cache.GetAsync(CacheKey.ExportFileName);
        }

        [HttpPost]
        [NonFormatResult]
        public async Task<ActionResult> ExprotFileAsync(string fileName)
        {
            var env = LazyGetRequiredService<IWebHostEnvironment>();
            var path = Path.Combine(env.WebRootPath, "Download", "Excel", fileName);

            if (!File.Exists(path))
            {
                await Cache.SetAsync(CacheKey.ExportProgress, 0);

                throw ResultOutput.Exception($"{fileName}文件不存在！");
            }
            await Cache.SetAsync(CacheKey.ExportProgress, 0);
            return new PhysicalFileResult(path, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = fileName
            };
        }

        /// <summary>
        /// 动态分表策略生成器
        /// </summary>
        private List<string> GetTableFilter(WorkStationRecordGetPageInput filter)
        {
            const string baseTableName = "prd_work_station_record";
            IEnumerable<string> GetShardingTables(DateTime start, DateTime end)
            {
                for (var month = start; month <= end; month = month.AddMonths(1))
                {
                    yield return $"{baseTableName}_{month:yyyyMM}";
                }
            }
            if (filter?.StartTime != null || filter?.EndTime != null)
            {
                var start = filter.StartTime?.Date ?? DateTime.MinValue;
                var end = filter.EndTime?.Date ?? new DateTime(9999, 12, 31);
                end = end.AddMonths(1).AddDays(-1);
                return GetShardingTables(start, end).Distinct().Reverse().ToList();
            }
            else
            {
                const int recentMonths = 1;
                var recentTables = Enumerable.Range(0, recentMonths)
                    .Select(i => DateTime.Now.AddMonths(-i))
                    .OrderByDescending(d => d) // 按时间倒序
                    .Select(d => $"{baseTableName}_{d:yyyyMM}");

                return recentTables.ToList();
            }
        }
    }
}